package com.trailwalker.inputmethod.dao;

import java.sql.*;

/**
 * @author Trailwalker
 * @create 2021-09-03 13:19
 * @des
 */
public class H2DatabaseUtils implements DatabaseInterface {

    /**
     * 数据库连接URL
     */
    private static final String JDBC_URL = "jdbc:h2:~/MediaPlayerDb";
    /**
     * 连接数据库时使用的用户名
     */
    private static final String USER = "Trailwalker";
    /**
     * 连接数据库时使用的密码
     */
    private static final String PASSWORD = "SHENGyi19961127";
    /**
     * 连接H2数据库时使用的驱动类
     */
    private static final String DRIVER_CLASS = "org.h2.Driver";
    private Connection conn = null;
    private Statement stmt = null;

    public H2DatabaseUtils(String jdbcUrl) {
        // 加载H2数据库驱动
        try {
            Class.forName(DRIVER_CLASS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // 根据连接URL，用户名，密码获取数据库连接
        try {
            conn = DriverManager.getConnection(jdbcUrl, USER, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                stmt = conn.createStatement();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean execute(String sql) {
        if (stmt != null) {
            try {
                return stmt.execute(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public int executeUpdate(String sql) {
        if (stmt != null) {
            try {
                return stmt.executeUpdate(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public ResultSet executeQuery(String sql) {
        if (stmt != null) {
            try {
                return stmt.executeQuery(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public void release() {
        //释放资源
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //关闭连接
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
